/**声音类：加载短促且对反应速度比较高的音频，使用SoundPool类
 * data 2011 5 10
 * author @zzy
 */
package cn.edu.dlut.WingGame.Sound;

import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
import cn.edu.dlut.WingGame.Game.WingGame;

public class WingSound {

	// final型变量，不能修改变量的值
	public static final int MAX_SOUNDS = 50; // 最多读取50个音乐文件
	public static final int MAX_STREAMS = 5; // 最多播放5道音乐

	public static WingSound soundPlay;

	private int i, j;
	private float volume;

	/*
	 * Android平台中关于平台播放有以下两种方式： SoundPool————适合短促且对反应速度比较高的情况（游戏音效或按键声音等）
	 * MediaPlayer————适合比较长且对时间要求不高的情况
	 */
	private SoundPool soundPool; // 声音播放类
	// SoundPool最大只能申请1M的内存空间

	private SoundFile[] soundArr = new SoundFile[MAX_SOUNDS];

	public static boolean mute = false; // 是否静音，静态变量

	public WingSound() {
		WingSound.soundPlay = this;
		soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
		volume = 1;
	}

	public SoundFile createSoundFile(String filename) {
		try {
			int id = soundPool.load(WingGame.getActivity().getAssets().openFd(
					filename), 0);
			SoundFile soundFile = new SoundFile(id);
			Log.v("SoundFile loaded as id =", "" + id);
			j = -1;
			for (i = 0; i < MAX_SOUNDS; i++) {
				if (soundArr[i] == null) {
					j = i;
					break;
				}
			}
			if (j == -1) {
				Log.v("TOO MANY SOUNDS", "" + j);
				return null;
			}
			soundArr[j] = soundFile;
			Log.v("SoundArr loaded as j =", "" + j);
			return soundFile;
		} catch (Exception e) {
			Log.v("CANNOT FIND ", filename);
			e.printStackTrace();
			return null;
		}
	}

	public void mute() { // 设置静音
		mute = true;
	}

	public void unMute() { // 取消静音
		mute = false;
	}

	public boolean isMuted() { // 判断是否静音
		return mute;
	}

	public void destroy() { // 被调用完后释放内存
		try {
			for (int i = 0; i < MAX_SOUNDS; ++i)
				soundArr[i].unload();
			soundPool.release();
		} catch (Exception e) {
			soundPool = null;
		}
	}

	public SoundFile[] getSounds() { // 获得指向当前音乐文件的哈希表
		return soundArr;
	}

	public SoundPool getSoundPool() { // 返回当前的声音类
		return soundPool;
	}

	public void removeFile(SoundFile soundFile) { // 从内存移去指定的音乐文件
		soundPool.unload(soundFile.getID());
		for (int i = 0; i < MAX_SOUNDS; ++i) {
			if (soundArr[i] != null) {
				if (soundArr[i].equals(soundFile))
					soundArr[i] = null;
			}

		}
	}

	public void removeAll() { // 从内存移去所有装入的音乐文件
		for (int i = 0; i < MAX_SOUNDS; ++i)
			soundArr[i] = null;
		soundPool.release();
	}

	public void setVolume(float volume) { // 设置当前流的声音
		this.volume = volume;
	}

	public float getVolume() { // 获取当前流的声音
		return this.volume;
	}

}
